package com.git.hui.yinshua.biz.user.service;

import com.alibaba.fastjson.JSONObject;
import com.git.hui.yinshua.api.model.user.UserBo;
import com.git.hui.yinshua.biz.rest.models.user.res.UserInfoDto;
import com.git.hui.yinshua.cache.redis.QuickRedisClient;
import com.git.hui.yinshua.common.SessionUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;

/**
 * @author YiHui
 * @date 2024/6/11
 */
@Service
public class UserSessionService {
    public static final String SESSION_COOKIE_KEY = "ys-token";

    private static String sessionCacheKey(String session) {
        return "ys_token_" + session;
    }

    /**
     * 保存用户session信息
     *
     * @param user
     * @return
     */
    public String saveSession(UserInfoDto user) {
        String session = SessionUtil.genSessionId();
        QuickRedisClient.putStr(sessionCacheKey(session), JSONObject.toJSONString(user));
        // 将sessionId写入cookie
        Cookie cookie = SessionUtil.newCookie(SESSION_COOKIE_KEY, session);
        // 回写cookie
        ((ServletRequestAttributes) (RequestContextHolder.getRequestAttributes())).getResponse().addCookie(cookie);
        return session;
    }


    /**
     * 更新缓存的用户信息
     *
     * @param session
     * @param user
     */
    public void updateSessionVal(String session, UserInfoDto user) {
        QuickRedisClient.putStr(sessionCacheKey(session), JSONObject.toJSONString(user));
    }

    /**
     * 查询用户信息
     *
     * @param sessionId
     * @return
     */
    public UserBo getUserVoBySessionId(String sessionId) {
        if (StringUtils.isBlank(sessionId)) {
            return null;
        }

        String user = QuickRedisClient.getStr(sessionCacheKey(sessionId));
        if (StringUtils.isNoneBlank(user)) {
            return JSONObject.parseObject(user, UserBo.class);
        }
        return null;
    }

    public void removeSession(String sessionId) {
        QuickRedisClient.delete(sessionCacheKey(sessionId));
    }
}
